package utils;

import play.Logger;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * JavaBean转换工具
 * 可用于将model转换成bean输出，选择输出的字段
 * @author chao
 * @since 2014/9/26
 */
public class BeanUtils {

    public static <T> T build(Class<T> beanClass, Object obj){
        Class source = obj.getClass();
        T bean;
        try{
            Constructor constructor = beanClass.getConstructor(obj.getClass());
            bean = (T)constructor.newInstance(obj);
        }catch(Exception ignore){
            try{
                bean = beanClass.newInstance();
            }catch (Exception e){
                Logger.error(e, "Error in build");
                return null;
            }

        }

        for(Field field: beanClass.getFields()){
            String name = field.getName();
            try{
                Field sourceField = source.getField(name);
                if(sourceField != null){
                    field.set(bean, sourceField.get(obj));
                }
            }catch (Exception e){
                //Logger.error(e, "Error in BeanUtils");
            }

        }
        return bean;
    }

    public static <T> List<T> buildList(Class<T> beanClass, List objs){
        List beans = new ArrayList();
        for(Object data: objs){
            beans.add(build(beanClass, data));
        }
        return beans;
    }
}
